package org.hdl.anima.proxy;

import org.hdl.anima.Application;
import org.hdl.anima.message.CreateLocalSessionReq;
import org.hdl.anima.message.CreateLocalSessionResp;
import org.hdl.anima.message.ResponseBinWrap;
import org.hdl.anima.message.ResponseObjWrap;
import org.hdl.anima.session.ClientSession;
import org.hdl.anima.session.ClientSessionMgr;
import org.hdl.anima.transport.Channel;
import org.hdl.anima.transport.RemoteException;
import org.hdl.anima.transport.support.ChannelHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author qiuhd
 * @since  2014年8月13日
 */
public class ServerProxyHanlder extends ChannelHandlerAdapter {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ServerProxyHanlder.class);
	private ClientSessionMgr clientSessionMgr;
	private final ServerProxy serverProxy;
	
	public ServerProxyHanlder(Application application,ServerProxy serverProxy) {
		this.clientSessionMgr = application.getMoulde(ClientSessionMgr.class);
		this.serverProxy = serverProxy;
	}

	@Override
	public void connected(Channel channel) throws RemoteException {
		CreateLocalSessionReq req = new CreateLocalSessionReq(serverProxy.getId());
		channel.send(req);
	}

	@Override
	public void sent(Channel channel, Object message) throws RemoteException {
		super.sent(channel, message);
	}

//	@Override
//	public void caught(Channel channel, Throwable cause)throws RemoteException {
//		LOGGER.error("Caught Excpetion:" + cause.getMessage(),cause);
//	}

	@Override
	public void disconnected(Channel channel) throws RemoteException {
		
	}

	@Override
	public void received(Channel channel, Object message) throws RemoteException {
		if (message instanceof CreateLocalSessionResp) {
			
		}else if (message instanceof ResponseBinWrap ){
			ResponseBinWrap wrap = (ResponseBinWrap)message;
			for (int receiver : wrap.getReceviers()) {
				ClientSession clientSession = clientSessionMgr.get(receiver);
				if (clientSession != null) {
					clientSession.send(wrap);
				}
			}
		}else if (message instanceof ResponseObjWrap) {
			ResponseObjWrap wrap = (ResponseObjWrap)message;
			for (int receiver : wrap.getReceivers().getReceivers()) {
				ClientSession clientSession = clientSessionMgr.get(receiver);
				if (clientSession != null) {
					clientSession.send(wrap);
				}
			}
		}
	}
}

